package com.woniu.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.exception.LXLGException;
import com.woniu.product.common.CouponResultCode;
import com.woniu.product.infra.model.CouponLogs;
import com.woniu.product.infra.mapper.CouponLogsMapper;
import com.woniu.product.service.CouponLogsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.product.service.form.AddCouponLogServiceParram;
import com.woniu.product.service.form.UpdateCouponLogServiceParam;
import com.woniu.util.DateUtil;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 优惠券消费记录表 服务实现类
 * </p>
 *
 * @author Lucas
 * @since 2022-11-26
 */
@Service
public class CouponLogsServiceImpl extends ServiceImpl<CouponLogsMapper, CouponLogs> implements CouponLogsService {

    /**
     * 新增优惠券记录
     *
     * @param addCouponLogServiceParram
     */
    @Override
    public void addCouponLog(AddCouponLogServiceParram addCouponLogServiceParram) {
        CouponLogs couponLogs = BeanUtil.copyProperties(addCouponLogServiceParram, CouponLogs.class);
        QueryWrapper<CouponLogs> qw = new QueryWrapper<>();
       qw.eq("coupon_receive_id", couponLogs.getCouponReceiveId()).eq("status", 1);
        CouponLogs logs = getOne(qw);
        if(logs!= null){
            throw new LXLGException(CouponResultCode.COUPONLOGS_HAVE_BEEN_RECORDED);
        }
        couponLogs.setCreateTime(new Date());
        couponLogs.setStatus(0);
        save(couponLogs);
    }

    /**
     * 修改优惠券记录
     *
     * @param updateCouponLogServiceParam
     */
    @Override
    public void updateCouponLog(UpdateCouponLogServiceParam updateCouponLogServiceParam) {
        QueryWrapper<CouponLogs> qw = new QueryWrapper<>();
        qw.eq("buyer_id", updateCouponLogServiceParam.getBuyerId()).eq("order_number", updateCouponLogServiceParam.getOrderNumber());
        List<CouponLogs> couponLogs = list(qw);
        if(couponLogs==null){
            throw new LXLGException(CouponResultCode.COUPONLOGS_NOT_FOUND);
        }
        for (CouponLogs c : couponLogs) {
            c.setStatus(1);
            updateById(c);
        }
    }
}
